package com.c1g19.action.common;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import java.util.Map;

import com.c1g19.action.BaseAction;
import com.c1g19.service.common.UserService;
import com.c1g19.utils.ConstCommon;
import com.c1g19.utils.MD5Util;
/**
 * Created by Mr_C on 2017/3/2.
 */
public class UserAction extends BaseAction{
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(UserAction.class);

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String prepareLogin() {
        return SUCCESS;
    }

    /**
     * 处理用户登录操作
     */
    public String userLogin() {
        logger.info("userLogin");
        if (StringUtils.isNotBlank(username)
                && StringUtils.isNotBlank(password)) {
            password=MD5Util.toMD5Code(password);
            if (StringUtils.isNotEmpty(password)) {
                UserService userService = new UserService();
                logger.info("userName:" + username);
                logger.info("password:" + password);
                Map<String, Object> userMap = userService.userLogin(username,
                        password);
                if (userMap == null || userMap.isEmpty()) {
                    setRequestAttribute("tip", "用户名或密码错误");
                    logger.info("用户名或密码错误");
                    return "failed";
                } else {
                    setSessionAttribute(ConstCommon.USERCONTEXT, userMap);
                    if(userMap.get("username").toString().equals("admin")){
                        return "admin";
                    }
                    return SUCCESS;
                }
            } else {
                setRequestAttribute("tip", "系统异常");
                return "failed";
            }
        } else {
            return "failed";
        }
    }

    public String userLogOut() {
        getRequest().getSession().invalidate();
        return SUCCESS;
    }
}